package com.zh.juc.threadlocal;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhanghuan
 * @date: 2022/10/25 20:09
 * @description: create it
 * 需求：5个销售卖房子，集团只关心销售的总量准确统计
 */
class House {
    public int saleCount = 0;

    public synchronized void saleHouse() {
        ++saleCount;
    }

    // ThreadLocal<Integer> saleVolume = new ThreadLocal<Integer>() {
    //     @Override
    //     protected Integer initialValue() {
    //         return 0;
    //     }
    // };
    ThreadLocal<Integer> saleVolume = ThreadLocal.withInitial(() -> 0);

    public void saleVolumeByThreadLocal() {
        saleVolume.set(saleVolume.get() + 1);
    }
}

public class ThreadLocalDemo {
    public static void main(String[] args) {

        House house = new House();

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                int size = new Random().nextInt(5) + 1;
                // System.out.println(size);
                for (int j = 0; j < size; j++) {
                    house.saleHouse();
                    house.saleVolumeByThreadLocal();
                }
                System.out.println(Thread.currentThread().getName() + "\t" + "号销售卖出：" + house.saleVolume.get());

            }, String.valueOf(i)).start();
        }

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "\t" + "共计卖出多少套" + house.saleCount);
    }
}
